package Simulator;

import java.util.Random;

public class Car {
	private int speed;
	private int cellIndex;
	private Road road;

	/**
	 * Constructor of Car
	 * Creates a new car and places it in the selected index of the road
	 * @param _road the road where the car will be placed
	 * @param _cellIndex the cell of the road 
	 */
	public Car(Road _road, int _cellIndex) {
		this.road = _road;
		this.cellIndex = _cellIndex;
		road.setCar(this, _cellIndex);
		Random random = new Random();
		this.speed = random.nextInt(road.getMaxSpeed());
	}

	/**
	 * Get the speed of the car
	 * 
	 * @return speed (int)
	 */
	public int getSpeed() {
		return speed;
	}
	/**
	 * set speed of the current car
	 */
	public void setSpeed(int speed) {
		this.speed = speed;
	}
	/**
	 * This is to check the distance for step 2
	 * 
	 * @return the distance to the next car
	 */
	public int getDistanceToNextCar() {
		int distance;
		Car nextCar = road.getNextCar(this);
		if (nextCar == null){
			distance = road.getLength();
		}else{
			distance = nextCar.getCellIndex() - cellIndex;
		}
		return distance;
	}
	/**
	 * This is step 1
	 * Speed of car is increased by 1 
	 */
	public void accelerate() {
		if(speed >= road.getMaxSpeed()){
			speed = road.getMaxSpeed();
		}else{
			speed++;
		}
	}
	
	/**
	 * This is step 2
	 * The speed of the car will be reduced to fit in the gap between itself and the next car
	 */
	public void decelerate(){
		int gap = getDistanceToNextCar() - 1;
		if (speed > gap){
			speed = gap;
		}
	}
	
	/**
	 * Step 3
	 * The speed will be decreased randomly by unit with probability
	 * @param _probability the probability, a float between 0 and 1
	 */
	public void randomizeSpeed(float _probability){
		Random random = new Random();
		int newSpeed = speed - 1;
		// check that speed will be always greater than 0
		if (newSpeed < 0) newSpeed = 0;
		// generate a random float and if is less than probability change speed
		// if greater do nothing, leave speed as is
		if (random.nextFloat() < _probability){
			speed = newSpeed;
		}
	}

	/**
	 * This is the step 4
	 * 
	 */
	public void moveCar() {
		int distance  = speed;
		road.moveCar(this, distance);
		cellIndex = cellIndex + distance;
	}
	
	public int getCellIndex(){
		return cellIndex;
	}
}
